import xlrd

from odoo import fields, models, api
from odoo.exceptions import UserError
# import pandas as pd
import base64
import csv
from io import StringIO

from ...functions.rp_translation_index_fc import RPTranslationIndexFC
from ...functions.rp_translation_table_fc import RPTranslationTableFC


class RPBackdoorTran(models.TransientModel):
    _name = 'rp.translation.upload.tran'
    _description = "翻译表导入"
    _rec_name = "code"

    def _default_auto_code(self):
        records = self.env['rp.translation.upload.tran'].search([])
        return "RP_TU" + str(len(records) + 1).zfill(3)

    code = fields.Char(string='索引码', default=_default_auto_code, index=True, copy=False, readonly=True)
    create_datetime = fields.Datetime(string='当前时间', default=fields.Datetime.now, copy=False, readonly=True)
    user_id = fields.Many2one(string='操作人', comodel_name='res.users', default=lambda self: self.env.user, copy=False, readonly=True)

    # 导入EXCEL文件
    excel_data = fields.Binary('EXCEL文件')
    csv_data = fields.Binary('CSV文件')
    file_name = fields.Char('名称')

    @api.model_create_multi
    def create(self, vals_list):
        for record in vals_list:
            if record.get('file_name'):
                suffix = record.get('file_name').split('.')[-1]
                if suffix not in ('xls', 'xlsx', 'csv'):
                    raise UserError('请上传正确的文件！')
                if suffix in ('xls', 'xlsx') and record.get('csv_data'):
                    raise UserError('请在正确位置上传！')
                if suffix == 'csv' and record.get('excel_data'):
                    raise UserError('请在正确位置上传！')
            else:
                raise UserError('请至少上传一项！')
        return super(RPBackdoorTran, self).create(vals_list)

    # 读取csv的逻辑
    def read_csv(self, csv_data):
        """
        读取csv
        @return csv_reader解析好的文件，headers表头
        """
        if self.csv_data:
            file_content = base64.b64decode(csv_data)
            file_content = StringIO(file_content.decode("utf-8"))
            csv_reader = csv.reader(file_content, delimiter=',')
            headers = next(csv_reader, None)  # 获取表头
            return csv_reader, headers
        else:
            raise UserError('请先上传必要的CSV文件！')

    # 读取Excel的逻辑
    def read_excel(self, excel_data):
        if excel_data:
            lines = []
            for record in self.get_data(excel_data):
                lines.append(record)
            return lines

    def get_data(self, excel_data):
        """读取excel"""
        file_data = base64.b64decode(excel_data)
        wb = xlrd.open_workbook(file_contents=file_data)
        sheet = wb.sheet_by_index(0)
        for i in range(1, sheet.nrows):
            row = sheet.row_values(i)
            stripped_row = [isinstance(i, str) and i.strip() or i for i in row]
            yield stripped_row

    def action_for_xlsx_csv_import_translation_data(self):
        # excel逻辑
        if self.excel_data:
            xlsx_list = self.read_excel(self.excel_data)
            self.upload_translation_data(xlsx_list)
        # csv校验
        if self.csv_data:
            csv_reader, headers = self.read_csv(self.csv_data)
            self.upload_translation_data(csv_reader)

    def upload_translation_data(self, list):
        """ 执行更新逻辑 """
        for record in list:
            # 1、获取数据
            _code = record[0] if len(record) >= 1 else False  # 编码
            _program = record[1] if len(record) >= 2 else False  # 项目
            _client = record[2] if len(record) >= 3 else False  # 终端
            _index = record[3] if len(record) >= 4 else False  # 索引
            _chinese = record[4] if len(record) >= 5 else False  # 中文
            _english = record[5] if len(record) >= 6 else False  # 英文
            _spanish = record[6] if len(record) >= 7 else False  # 西语
            _catalan = record[7] if len(record) >= 8 else False  # 加泰罗尼亚语

            # 2、可更新依据
            if not all([_code, _program, _client, _index]):
                continue
            # 3、获取项目
            program = self.env['rp.translation.program'].search([('name', '=', _program)])
            if not program:
                continue
            # 4、获取终端
            client = self.env['rp.translation.client'].search([('name', '=', _client)])
            if not client:
                continue
            # 5、更新翻译对照表记录
            update_rcd = RPTranslationTableFC(self.env).update_table(program=program, client=client, index=_index,
                                                                     chinese=_chinese, english=_english, spanish=_spanish, catalan=_catalan)
            print(update_rcd)
